<!--"用户列表"  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clean='getUsersList'>
            <el-button slot="append" icon="el-icon-search" @click="getQueryAboutList" ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6"><el-button type="primary" @click="dialogVisible = true">添加用户</el-button></el-col>
      </el-row>
      <el-table :data="userList" border style="width: 100%" stripe index>
        <el-table-column
          type="index"
          label="#"
          width="80">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="120">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          width="150">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template  slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable='false'>
              <el-button type="primary" icon="el-icon-edit" size="small" @click="btnEditClick(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable='false'>
              <el-button type="danger" icon="el-icon-delete" size="small" @click="btnDeleteClick(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable='false'>
              <el-button type="success" icon="el-icon-setting" size="small" @click="btnSettingClick(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部分页 -->
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[1,2,5,10,50]"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户"  :visible.sync="dialogVisible" :close-on-click-modal="false"
      width="50%"
      @close="addDialogClosed">
      <!-- dialog主题区域 -->
      <el-form :model="addForm" :rules="addFormRules"
        ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" >
          <el-input type="password" v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" >
          <el-input v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone" >
          <el-input v-model="addForm.phone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserDialogClick">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户信息"  :visible.sync="dialogEditVisible"
      width="50%"
      @close="editDialogClosed">
      <!-- dialog主题区域 -->
      <el-form :model="editForm" :rules="editFormRules"
        ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" >
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone" >
          <el-input  v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserDialogClick">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="用户权限分配"  :visible.sync="dialogRoleVisible"
      width="50%"
      @close="roleDialogClosed">
      <!-- dialog主题区域 -->
      <div>
        <p>当前用户：{{users.username}}</p>
        <p>当前角色：{{users.role_name}}</p>
        <p>
          <el-select v-model="selectRoleId" placeholder="请选择角色权限">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="rolesDialogClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    var checkMobile = (rule, value, callback) => {
      const refMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (refMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 添加dialog 显示
      dialogVisible: false,
      // 修改dialog显示隐藏
      dialogEditVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        phone: ''
      },
      // 添加表单规则验证对象
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '用户名自长度在3-10之间',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '密码长度在6-15之间',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱地址',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      editForm: {},
      editFormRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱地址',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      // 分配权限dialog显示和隐藏
      dialogRoleVisible: false,
      users: {},
      // 获取所有权限角色
      rolesList: [],
      // 分配权限选中角色id值
      selectRoleId: ''
    }
  },
  created () {
    // 获取用户列表数据
    this.getUsersList()
  },
  methods: {
    // 请求用户数据
    async getUsersList () {
      let { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      // console.log(res)
      this.total = res.data.total
    },
    // 每页多少条
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      // console.log(`每页 ${val} 条`)
      this.getUsersList()
    },
    // 当前页
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      this.getUsersList()
    },
    // 搜索
    getQueryAboutList () {
      // console.log(this.queryInfo.query)
      this.getUsersList()
    },
    // 编辑状态点击事件
    async btnEditClick (row) {
      // console.log('编辑' + id)
      let { data: res } = await this.$http.get('users/' + row.id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('状态更新失败')
      }
      this.editForm = res.data
      this.dialogEditVisible = true
    },
    // 删除用户点击事件
    async btnDeleteClick (scope) {
      // console.log('删除' + scope.id)
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      let { data: res } = await this.$http.delete('users/' + scope)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getUsersList()
    },
    // 设置权限点击事件
    async btnSettingClick (scope) {
      // console.log('设置' + scope.id)
      this.users = scope
      let { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
        return
      }
      this.rolesList = res.data
      this.dialogRoleVisible = true
    },
    // 更新用户状态
    async userStateChange (user) {
      let { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        return this.$message.error('状态更新失败')
      }
      this.$message.success('状态更新成功')
    },
    // 监听用户对话框关闭
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 对话框添加用户窗口
    addUserDialogClick () {
      this.$refs.addFormRef.validate(async (isTrue, obj) => {
        if (!isTrue) return
        let { data: res } = await this.$http.post('users', {
          'username': this.addForm.username,
          'password': this.addForm.password,
          'email': this.addForm.email,
          'mobile': this.addForm.phone
        })
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
          return
        }
        this.$message.success('添加用户成功！')
        this.dialogVisible = false
        this.getUsersList()
      })
    },
    // 编辑用户dialog点击事件
    editUserDialogClick () {
      // sss
      this.$refs.editForm.validate(async (isTrue, obj) => {
        if (!isTrue) return
        let { data: res } = await this.$http.put('users/' + this.editForm.id, {
          'email': this.editForm.email,
          'mobile': this.editForm.phone
        })
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户失败')
        }
        this.$message.success('更新用户成功！')
        this.dialogVisible = false
        this.getUsersList()
      })
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    async rolesDialogClick () {
      if (!this.selectRoleId) {
        return this.$message.error('请选择分配的角色')
      }
      let { data: res } = await this.$http.put(`users/${this.users.id}/role`, {
        rid: this.selectRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配用户角色失败')
      }
      this.$message.success('分配用户角成功！')
      this.getUsersList()
      this.dialogRoleVisible = false
    },
    roleDialogClosed () {
      this.selectRoleId = ''
      this.users = {}
    }
  }
}

</script>
<style lang='less' scoped>
</style>
